﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QXBook.Model;
using System.Data;
using QXBook.Utils;
using System.Data.Common;
using System.Data.SqlClient;

namespace QXBook.Service
{
    /// <summary>
    /// 使用字典方便查询popdomstr，ContainsKey方法时间复杂度为0
    /// </summary>
    public class AdminRuleService : ServiceBase
    {
        /// <summary>
        /// 获得所有管理组实体
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, MembersRoleInfo> GetAllAdminRoleEntity()
        {
            Dictionary<int, MembersRoleInfo> alladminrole = (Dictionary<int, MembersRoleInfo>)CachingService.Get(CachingService.CACHING_ALL_ADMINROLE_ENTITY);
            if (alladminrole == null)
            {
                DataTable dt = GetALLAdminRole();
                if (dt == null) return null;
                if (dt.Rows.Count == 0) return null;
                alladminrole = new Dictionary<int, MembersRoleInfo>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow Row = dt.Rows[i];
                    MembersRoleInfo role = new MembersRoleInfo();

                    role.RoleID = (int)Row["RoleID"];
                    role.RoleName = Row["RoleName"].ToString();
                    role.Content = Row["Content"].ToString();
                    role.PopDomList = this.GetPopDomsByIDs(Row["PopDomList"].ToString());
                    role.PopDomStr = Row["PopDomList"].ToString();
                    role.UpdateDate = CommonUtils.ToTime(Row["UpdateDate"].ToString());

                    alladminrole.Add(role.RoleID, role);
                }

                CachingService.Set(CachingService.CACHING_ALL_ADMINROLE_ENTITY, alladminrole, null);
            }
            return alladminrole;
        }

        /// <summary>
        /// 根据权限组ID获取权限组信息
        /// </summary>
        /// <param name="iRoleId"></param>
        /// <returns></returns>
        public MembersRoleInfo GetAdminRoleInfoByRoleId(int iRoleId)
        {
            Dictionary<int, MembersRoleInfo> allRole = this.GetAllAdminRoleEntity();
            if (allRole == null) return null;
            if (allRole.Count == 0) return null;
            if (!allRole.ContainsKey(iRoleId)) return null;
            return allRole[iRoleId];
        }

        /// <summary>
        /// 获得所有管理角色
        /// </summary>
        /// <returns></returns>
        public DataTable GetALLAdminRole()
        {
            string sql = "SELECT RoleID,RoleName,Content,PopDomList,UpdateDate FROM MembersRole";
            DataSet ds = base.db.ExecuteDataSet(CommandType.Text, sql);
            return ds != null ? ds.Tables[0] : null;
        }

        /// <summary>
        /// 获得角色组基本信息
        /// </summary>
        /// <param name="admincount"></param>
        /// <param name="ds"></param>
        /// <returns></returns>
        public int GetAdminRoleInfo(ref int rolecount, ref DataSet ds)
        {
            string rolecountsql = "SELECT COUNT(1) FROM MembersRole";
            string allrolesql = "SELECT RoleID,RoleName,(SELECT COUNT(1) FROM Members WHERE [RoleID]= A.RoleID AND IsDelete<>" + (int)YesNo.Yes + ") AS [num],UpdateDate  FROM MembersRole A ";

            rolecount = CommonUtils.ToInt(base.db.ExecuteScalar(CommandType.Text, rolecountsql));
            ds = base.db.ExecuteDataSet(CommandType.Text, allrolesql);
            return 1;
        }

        /// <summary>
        /// 添加新的角色组
        /// </summary>
        /// <param name="vcAdminname"></param>
        /// <param name="vcRoleName"></param>
        /// <param name="pop"></param>
        /// <param name="classpop"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public string AddAdminRole(MembersInfo Admin, MembersRoleInfo role)
        {
            if (string.IsNullOrEmpty(role.RoleName))
            {
                return MsgConst.ADMINROLE_NAMENULL;
            }

            string rtmessage = ServiceFactory.CreateInstance<AdminService>().CheckAdminPower(Admin);
            if (!string.IsNullOrEmpty(rtmessage)) return rtmessage;

            DbCommand cmd = new SqlCommand("INSERT INTO MembersRole (RoleName,Content,PopDomList,UpdateDate) "
                    + "VALUES(@RoleName,@Content,@PopDomList,GETDATE()) ");
            base.db.AddInParameter(cmd, "@RoleName", DbType.String, role.RoleName);
            base.db.AddInParameter(cmd, "@Content", DbType.String, role.Content);
            base.db.AddInParameter(cmd, "@PopDomList", DbType.String, role.PopDomStr);

            base.db.ExecuteNonQuery(cmd);
            return string.Empty;
        }

        /// <summary>
        /// 修改角色组
        /// </summary>
        /// <param name="vcAdminname"></param>
        /// <param name="vcRoleName"></param>
        /// <param name="pop"></param>
        /// <param name="classpop"></param>
        /// <param name="content"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public string UpdateAdminRole(MembersInfo Admin, MembersRoleInfo role)
        {
            if (string.IsNullOrEmpty(role.RoleName))
            {
                return MsgConst.ADMINROLE_NAMENULL;
            }

            string rtmessage = ServiceFactory.CreateInstance<AdminService>().CheckAdminPower(Admin);
            if (!string.IsNullOrEmpty(rtmessage)) return rtmessage;

            DbCommand cmd = new SqlCommand("UPDATE MembersRole SET RoleName=@RoleName, Content=@Content, PopDomList=@PopDomList, UpdateDate=GETDATE() WHERE RoleID=" + role.RoleID.ToString());
            base.db.AddInParameter(cmd, "@RoleName", DbType.String, role.RoleName);
            base.db.AddInParameter(cmd, "@Content", DbType.String, role.Content);
            base.db.AddInParameter(cmd, "@PopDomList", DbType.String, role.PopDomStr);
            base.db.ExecuteNonQuery(cmd);

            cmd.CommandText = "UPDATE Members SET IsOnline=" + (int)YesNo.No + " WHERE RoleID=" + role.RoleID.ToString();
            base.db.ExecuteNonQuery(cmd);
            return string.Empty;
        }

        /// <summary>
        /// 删除角色组
        /// </summary>
        /// <param name="vcAdminname"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public string DelAdminRole(MembersInfo Admin, int roleid)
        {
            string rtmessage = ServiceFactory.CreateInstance<AdminService>().CheckAdminPower(Admin);
            if (!string.IsNullOrEmpty(rtmessage)) return rtmessage;

            if (roleid == 0)
            {
                return MsgConst.ADMINROLE_ROLEIDNULL;
            }

            int admincount = CommonUtils.ToInt(base.db.ExecuteScalar(CommandType.Text, "SELECT COUNT(1) FROM Members WHERE RoleID=" + roleid));
            if (admincount > 0)
            {
                return MsgConst.ADMINROLE_NEEDREMOVE_ADMIN;
            }

            base.db.ExecuteNonQuery(CommandType.Text, "DELETE FROM MembersRole WHERE RoleID = " + roleid);
            return string.Empty;
        }

        /// <summary>
        /// 获得所有权限项
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, PopDomInfo> GetAllPopedomEntity()
        {
            Dictionary<int, PopDomInfo> allpop = (Dictionary<int, PopDomInfo>)CachingService.Get(CachingService.CACHING_ALL_POPDOM);
            if (allpop == null)
            {
                DataTable dt = GetAllPopedom();
                if (dt == null) return null;
                allpop = this.GetPopedomsEntityFromDataTable(dt);
                CachingService.Set(CachingService.CACHING_ALL_POPDOM, allpop, null);
            }
            return allpop;
        }

        /// <summary>
        /// 获得后台管理的菜单项目
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, PopDomInfo> GetManagePopedomEntity()
        {
            Dictionary<int, PopDomInfo> allpop = this.GetAllPopedomEntity();
            if (allpop == null) return null;
            if (allpop.Count == 0) return null;
            Dictionary<int, PopDomInfo> managepop = new Dictionary<int, PopDomInfo>();
            foreach (KeyValuePair<int, PopDomInfo> keyvalue in allpop)
            {
                managepop.Add(keyvalue.Key, keyvalue.Value);
            }
            return managepop;
        }

        /// <summary>
        /// 获得子权限
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public Dictionary<int, PopDomInfo> GetChildManagePopedomEntity(int pid)
        {
            Dictionary<int, PopDomInfo> managepop = this.GetManagePopedomEntity();
            if (managepop == null) return null;
            Dictionary<int, PopDomInfo> cmpop = new Dictionary<int, PopDomInfo>();
            foreach (KeyValuePair<int, PopDomInfo> keyvalue in managepop)
            {
                if (keyvalue.Value.ParentId == pid)
                {
                    cmpop.Add(keyvalue.Key, keyvalue.Value);
                }
            }
            return cmpop;
        }

        /// <summary>
        /// 获得部分权限选项目
        /// </summary>
        /// <param name="iIds"></param>
        /// <returns></returns>
        public Dictionary<int, PopDomInfo> GetPopDomsByIDs(string iIds)
        {
            Dictionary<int, PopDomInfo> allpop = this.GetAllPopedomEntity();
            if (allpop == null) return null;
            if (allpop.Count == 0) return null;
            Dictionary<int, PopDomInfo> pops = new Dictionary<int, PopDomInfo>();
            if (iIds.IndexOf(",") > -1)
            {
                string[] ids = iIds.Split(',');
                for (int i = 0; i < ids.Length; i++)
                {
                    int tid = CommonUtils.ToInt(ids[i]);
                    if (allpop.ContainsKey(tid))
                    {
                        pops.Add(tid, allpop[tid]);
                    }
                }
            }
            else
            {
                int id = CommonUtils.ToInt(iIds);
                if (allpop.ContainsKey(id))
                {
                    pops.Add(id, allpop[id]);
                }
            }

            return (pops.Count == 0) ? null : pops;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rid"></param>
        /// <param name="iIds"></param>
        /// <returns></returns>
        public Dictionary<int, PopDomInfo> GetAdminPopDomsByID(MembersRoleInfo adminrole, string Ids)
        {
            if (adminrole == null) return null;
            Dictionary<int, PopDomInfo> allpop = this.GetAllPopedomEntity();
            if (allpop == null) return null;
            if (allpop.Count == 0) return null;
            Dictionary<int, PopDomInfo> pops = new Dictionary<int, PopDomInfo>();
            if (Ids.IndexOf(",") > -1)
            {
                string[] ids = Ids.Split(',');
                for (int i = 0; i < ids.Length; i++)
                {
                    int tid = CommonUtils.ToInt(ids[i]);
                    if (allpop.ContainsKey(tid))
                    {
                        pops.Add(tid, allpop[tid]);
                    }
                }
            }
            else
            {
                int id = CommonUtils.ToInt(Ids);
                if (allpop.ContainsKey(id))
                {
                    pops.Add(id, allpop[id]);
                }
            }

            if (adminrole.PopDomStr != null && adminrole.PopDomList.Count != 0)
            {
                foreach (KeyValuePair<int, PopDomInfo> keyvalue in adminrole.PopDomList)
                {
                    if (!pops.ContainsKey(keyvalue.Key))
                    {
                        pops.Add(keyvalue.Key, keyvalue.Value);
                    }
                }
            }

            return (pops.Count == 0) ? null : pops;
        }

        /// <summary>
        /// 获得所有权限实体
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public Dictionary<int, PopDomInfo> GetPopedomsEntityFromDataTable(DataTable dt)
        {
            if (dt == null) return null;
            if (dt.Rows.Count == 0) return null;
            Dictionary<int, PopDomInfo> allpopedom = new Dictionary<int, PopDomInfo>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow Row = dt.Rows[i];
                PopDomInfo pop = new PopDomInfo();

                pop.PopID = CommonUtils.ToInt(Row["popid"].ToString());
                pop.PopName = Row["popname"].ToString();
                pop.ParentId = CommonUtils.ToInt(Row["parentid"].ToString());
                pop.IconKey = CommonUtils.ToString(Row["iconkey"].ToString());
                pop.Url = Row["url"].ToString();

                allpopedom.Add(pop.PopID, pop);
            }
            return allpopedom;
        }

        /// <summary>
        /// 获得所有权限选项目
        /// </summary>
        /// <returns></returns>
        public DataTable GetAllPopedom()
        {
            DataSet dsxml = new DataSet();
            dsxml.ReadXml(System.Web.HttpContext.Current.Server.MapPath(this.PopDomXmlPath));
            //return DataBaseFactory.AdminHandlers.GetAllPopedom();
            return dsxml.Tables[0];
        }

        private string PopDomXmlPath = "~/Config/PopDom.config";
    }
}
